package com.han.neo4jjava.mysql.person;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.han.neo4jjava.core.person.Person;
import com.han.neo4jjava.core.person.PersonRepo;
import com.han.neo4jjava.mysql.personLocationRelation.PersonLocationRelationMapper;
import com.han.neo4jjava.mysql.location.LocationMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.List;

import static java.util.stream.Collectors.toList;

@Component
@RequiredArgsConstructor
public class MysqlPersonRepoImpl implements PersonRepo {

    private final PersonMapper personMapper;
    private final LocationMapper locationMapper;
    private final PersonLocationRelationMapper personLocationRelationMapper;

    @Override
    public List<Person> findAll() {
        List<PersonModel> models = personMapper.selectList(null);
        return models.stream().map(this::convert2Person).collect(toList());
    }

    @Override
    public List<Person> queryAllByName(String name) {
        QueryWrapper<PersonModel> wrapper = new QueryWrapper<>();
        wrapper.eq("name", name);
        List<PersonModel> models = personMapper.selectList(wrapper);
        return models.stream().map(this::convert2Person).collect(toList());
    }

    @Override
    public void drop() {
        personMapper.delete(null);
        locationMapper.delete(null);
        personLocationRelationMapper.delete(null);
    }

    @Override
    public void saveAll(List<Person> persons) {
        persons.stream().map(this::convert2PersonModel).forEach(personMapper::insert);
    }

    @Override
    public void save(Person person) {

    }

    private PersonModel convert2PersonModel(Person person) {
        PersonModel model = new PersonModel();
        model.setId(person.getId());
        model.setName(person.getName());
        return model;
    }

    private Person convert2Person(PersonModel model) {
        Person person = new Person();
        person.setId(model.getId());
        person.setName(model.getName());
        return person;
    }
}
